import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;

import java.io.File;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * http://www.developer.com/java/how-to-create-database-reports-through-jasperreport.html
 * 使用 jdbc 数据库链接作为数据源
 */
public class DataSourceJDBC {
    private static File CLASS_PATH_ROOT_DIR = null;
    Connection con;
    String jdbcUrl = "jdbc:mysql://104.236.132.55:3306/appbricks?useUnicode=true&characterEncoding=utf-8&useSSL=false";
    String username = "root";
    String password = "ab_mysql_v3";
    String jasperFile="/jasper/ds_jdbc.jasper";

    static {
        try {
            CLASS_PATH_ROOT_DIR = new File(DataSourceJDBC.class.getResource("/").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }



    public void createReport() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(jdbcUrl, username, password);
            JasperPrint jp;
            jp = JasperFillManager.fillReport(CLASS_PATH_ROOT_DIR + jasperFile, new HashMap(), con);
            JasperViewer jv = new JasperViewer(jp);
            jv.setVisible(true);
            con.close();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (JRException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new DataSourceJDBC().createReport();
    }

}